

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>1.18 映射名称到序列元素 &mdash; python3-cookbook 3.0.0 documentation</title>
  

  
  
  
  

  

  
  
    

  

  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="1.19 转换并同时计算数据" href="p19_transform_and_reduce_data_same_time.html" />
    <link rel="prev" title="1.17 从字典中提取子集" href="p17_extract_subset_of_dict.html" /> 

  
  <script src="../_static/js/modernizr.min.js"></script>

</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search">
          

          
            <a href="../index.html" class="icon icon-home"> python3-cookbook
          

          
          </a>

          
            
            
              <div class="version">
                3.0
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul class="current">
<li class="toctree-l1 current"><a class="reference internal" href="../chapters/p01_data_structures_algorithms.html">第一章：数据结构和算法</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="p01_unpack_sequence_into_separate_variables.html">1.1 解压序列赋值给多个变量</a></li>
<li class="toctree-l2"><a class="reference internal" href="p02_unpack_elements_from_iterables.html">1.2 解压可迭代对象赋值给多个变量</a></li>
<li class="toctree-l2"><a class="reference internal" href="p03_keep_last_n_items.html">1.3 保留最后 N 个元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p04_find_largest_or_smallest_n_items.html">1.4 查找最大或最小的 N 个元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p05_implement_a_priority_queue.html">1.5 实现一个优先级队列</a></li>
<li class="toctree-l2"><a class="reference internal" href="p06_map_keys_to_multiple_values_in_dict.html">1.6 字典中的键映射多个值</a></li>
<li class="toctree-l2"><a class="reference internal" href="p07_keep_dict_in_order.html">1.7 字典排序</a></li>
<li class="toctree-l2"><a class="reference internal" href="p08_calculating_with_dict.html">1.8 字典的运算</a></li>
<li class="toctree-l2"><a class="reference internal" href="p09_find_commonalities_in_dicts.html">1.9 查找两字典的相同点</a></li>
<li class="toctree-l2"><a class="reference internal" href="p10_remove_duplicates_from_seq_order.html">1.10 删除序列相同元素并保持顺序</a></li>
<li class="toctree-l2"><a class="reference internal" href="p11_naming_slice.html">1.11 命名切片</a></li>
<li class="toctree-l2"><a class="reference internal" href="p12_determine_most_freqently_items_in_seq.html">1.12 序列中出现次数最多的元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p13_sort_list_of_dicts_by_key.html">1.13 通过某个关键字排序一个字典列表</a></li>
<li class="toctree-l2"><a class="reference internal" href="p14_sort_objects_without_compare_support.html">1.14 排序不支持原生比较的对象</a></li>
<li class="toctree-l2"><a class="reference internal" href="p15_group_records_based_on_field.html">1.15 通过某个字段将记录分组</a></li>
<li class="toctree-l2"><a class="reference internal" href="p16_filter_sequence_elements.html">1.16 过滤序列元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p17_extract_subset_of_dict.html">1.17 从字典中提取子集</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">1.18 映射名称到序列元素</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#id2">问题</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id3">解决方案</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id4">讨论</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="p19_transform_and_reduce_data_same_time.html">1.19 转换并同时计算数据</a></li>
<li class="toctree-l2"><a class="reference internal" href="p20_combine_multiple_map_to_single_map.html">1.20 合并多个字典或映射</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../chapters/p02_strings_and_text.html">第二章：字符串和文本</a></li>
<li class="toctree-l1"><a class="reference internal" href="../aboutme.html">关于</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../index.html">python3-cookbook</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../chapters/p01_data_structures_algorithms.html">第一章：数据结构和算法</a> &raquo;</li>
        
      <li>1.18 映射名称到序列元素</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="../_sources/c01/p18_map_names_to_sequence_elements.rst.txt" rel="nofollow"> View page source</a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="id1">
<h1>1.18 映射名称到序列元素<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h1>
<div class="section" id="id2">
<h2>问题<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>你有一段通过下标访问列表或者元组中元素的代码，但是这样有时候会使得你的代码难以阅读，
于是你想通过名称来访问元素。</p>
</div>
<div class="section" id="id3">
<h2>解决方案<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">collections.namedtuple()</span></code> 函数通过使用一个普通的元组对象来帮你解决这个问题。
这个函数实际上是一个返回 Python 中标准元组类型子类的一个工厂方法。
你需要传递一个类型名和你需要的字段给它，然后它就会返回一个类，你可以初始化这个类，为你定义的字段传递值等。
代码示例：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">namedtuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Subscriber</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Subscriber&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;addr&#39;</span><span class="p">,</span> <span class="s1">&#39;joined&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sub</span> <span class="o">=</span> <span class="n">Subscriber</span><span class="p">(</span><span class="s1">&#39;jonesy@example.com&#39;</span><span class="p">,</span> <span class="s1">&#39;2012-10-19&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sub</span>
<span class="go">Subscriber(addr=&#39;jonesy@example.com&#39;, joined=&#39;2012-10-19&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sub</span><span class="o">.</span><span class="n">addr</span>
<span class="go">&#39;jonesy@example.com&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sub</span><span class="o">.</span><span class="n">joined</span>
<span class="go">&#39;2012-10-19&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>尽管 <code class="docutils literal notranslate"><span class="pre">namedtuple</span></code> 的实例看起来像一个普通的类实例，但是它跟元组类型是可交换的，支持所有的普通元组操作，比如索引和解压。
比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">sub</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">addr</span><span class="p">,</span> <span class="n">joined</span> <span class="o">=</span> <span class="n">sub</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">addr</span>
<span class="go">&#39;jonesy@example.com&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">joined</span>
<span class="go">&#39;2012-10-19&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>命名元组的一个主要用途是将你的代码从下标操作中解脱出来。
因此，如果你从数据库调用中返回了一个很大的元组列表，通过下标去操作其中的元素，
当你在表中添加了新的列的时候你的代码可能就会出错了。但是如果你使用了命名元组，那么就不会有这样的顾虑。</p>
<p>为了说明清楚，下面是使用普通元组的代码：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">compute_cost</span><span class="p">(</span><span class="n">records</span><span class="p">):</span>
    <span class="n">total</span> <span class="o">=</span> <span class="mf">0.0</span>
    <span class="k">for</span> <span class="n">rec</span> <span class="ow">in</span> <span class="n">records</span><span class="p">:</span>
        <span class="n">total</span> <span class="o">+=</span> <span class="n">rec</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="n">rec</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">total</span>
</pre></div>
</div>
<p>下标操作通常会让代码表意不清晰，并且非常依赖记录的结构。
下面是使用命名元组的版本：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">namedtuple</span>

<span class="n">Stock</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Stock&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;shares&#39;</span><span class="p">,</span> <span class="s1">&#39;price&#39;</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">compute_cost</span><span class="p">(</span><span class="n">records</span><span class="p">):</span>
    <span class="n">total</span> <span class="o">=</span> <span class="mf">0.0</span>
    <span class="k">for</span> <span class="n">rec</span> <span class="ow">in</span> <span class="n">records</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">Stock</span><span class="p">(</span><span class="o">*</span><span class="n">rec</span><span class="p">)</span>
        <span class="n">total</span> <span class="o">+=</span> <span class="n">s</span><span class="o">.</span><span class="n">shares</span> <span class="o">*</span> <span class="n">s</span><span class="o">.</span><span class="n">price</span>
    <span class="k">return</span> <span class="n">total</span>
</pre></div>
</div>
</div>
<div class="section" id="id4">
<h2>讨论<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<p>命名元组另一个用途就是作为字典的替代，因为字典存储需要更多的内存空间。
如果你需要构建一个非常大的包含字典的数据结构，那么使用命名元组会更加高效。
但是需要注意的是，不像字典那样，一个命名元组是不可更改的。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span>&gt;&gt;&gt; s = Stock(&#39;ACME&#39;, 100, 123.45)
&gt;&gt;&gt; s
Stock(name=&#39;ACME&#39;, shares=100, price=123.45)
&gt;&gt;&gt; s.shares = 75
Traceback (most recent call last):
File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
AttributeError: can&#39;t set attribute
&gt;&gt;&gt;
</pre></div>
</div>
<p>如果你真的需要改变属性的值，那么可以使用命名元组实例的 <code class="docutils literal notranslate"><span class="pre">_replace()</span></code> 方法，
它会创建一个全新的命名元组并将对应的字段用新的值取代。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">shares</span><span class="o">=</span><span class="mi">75</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span>
<span class="go">Stock(name=&#39;ACME&#39;, shares=75, price=123.45)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">_replace()</span></code> 方法还有一个很有用的特性就是当你的命名元组拥有可选或者缺失字段时候，
它是一个非常方便的填充数据的方法。
你可以先创建一个包含缺省值的原型元组，然后使用 <code class="docutils literal notranslate"><span class="pre">_replace()</span></code> 方法创建新的值被更新过的实例。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">namedtuple</span>

<span class="n">Stock</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Stock&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;shares&#39;</span><span class="p">,</span> <span class="s1">&#39;price&#39;</span><span class="p">,</span> <span class="s1">&#39;date&#39;</span><span class="p">,</span> <span class="s1">&#39;time&#39;</span><span class="p">])</span>

<span class="c1"># Create a prototype instance</span>
<span class="n">stock_prototype</span> <span class="o">=</span> <span class="n">Stock</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>

<span class="c1"># Function to convert a dictionary to a Stock</span>
<span class="k">def</span> <span class="nf">dict_to_stock</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">stock_prototype</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="o">**</span><span class="n">s</span><span class="p">)</span>
</pre></div>
</div>
<p>下面是它的使用方法：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;ACME&#39;</span><span class="p">,</span> <span class="s1">&#39;shares&#39;</span><span class="p">:</span> <span class="mi">100</span><span class="p">,</span> <span class="s1">&#39;price&#39;</span><span class="p">:</span> <span class="mf">123.45</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dict_to_stock</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">Stock(name=&#39;ACME&#39;, shares=100, price=123.45, date=None, time=None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;ACME&#39;</span><span class="p">,</span> <span class="s1">&#39;shares&#39;</span><span class="p">:</span> <span class="mi">100</span><span class="p">,</span> <span class="s1">&#39;price&#39;</span><span class="p">:</span> <span class="mf">123.45</span><span class="p">,</span> <span class="s1">&#39;date&#39;</span><span class="p">:</span> <span class="s1">&#39;12/17/2012&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dict_to_stock</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="go">Stock(name=&#39;ACME&#39;, shares=100, price=123.45, date=&#39;12/17/2012&#39;, time=None)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>最后要说的是，如果你的目标是定义一个需要更新很多实例属性的高效数据结构，那么命名元组并不是你的最佳选择。
这时候你应该考虑定义一个包含 <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> 方法的类（参考8.4小节）。</p>
</div>
</div>


           </div>
           
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="p19_transform_and_reduce_data_same_time.html" class="btn btn-neutral float-right" title="1.19 转换并同时计算数据" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="p17_extract_subset_of_dict.html" class="btn btn-neutral" title="1.17 从字典中提取子集" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2017, 熊能.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
            URL_ROOT:'../',
            VERSION:'3.0.0',
            LANGUAGE:'None',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: '.txt'
        };
    </script>
      <script type="text/javascript" src="../_static/jquery.js"></script>
      <script type="text/javascript" src="../_static/underscore.js"></script>
      <script type="text/javascript" src="../_static/doctools.js"></script>

  

  <script type="text/javascript" src="../_static/js/theme.js"></script>

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script> 

</body>
</html>